/*
 * Copyright ShangHai ECLUB Information Technology Co.,Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at

 * http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.eclub.emotion.rootstone.server.util;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.eclub.emotion.rootstone.server.annotation.RsServiceMethod;
import com.eclub.emotion.rootstone.server.annotation.RsServiceMethodBean;
import com.eclub.emotion.rootstone.server.http.mapping.ServiceMethodHandler;

/**
 * 
 * TODO Description
 *
 * @author   jun.yang, Wincor Nixdorf International GmbH
 */
public class Scans {
	Logger LOGGER = Logger.getLogger(this.getClass());
	private static final Scans me = new Scans();

	private Scans() {
	}

	public static Scans me() {
		return me;
	}

	public Map<String, ServiceMethodHandler> scan(String[] directory, ClassLoader classLoader) throws ClassNotFoundException {
		Map<String, ServiceMethodHandler> serviceMethodHandlerMap = new HashMap<String, ServiceMethodHandler>();
		List<Class<?>> clazzList = ClassTools.loadClass(directory, classLoader);
		for (Class<?> clazz : clazzList) {
			RsServiceMethodBean serviceMethodBean = clazz.getAnnotation(RsServiceMethodBean.class);
			if (serviceMethodBean != null) {
				Method[] methods = clazz.getMethods();
				for (int i = 0; i < methods.length; i++) {
					Method method = methods[i];
					RsServiceMethod serviceMethod = method.getAnnotation(RsServiceMethod.class);
					if (serviceMethod != null) {
						ServiceMethodHandler handler = new ServiceMethodHandler();
						handler.setHandlerClazz(clazz);
						handler.setHandlerMethod(method);
						handler.setHandlerMethodName(StringUtils.isEmpty(serviceMethod.method()) ? method.getName() : serviceMethod.method());
						serviceMethodHandlerMap.put(handler.getHandlerMethodName(), handler);
					}
				}
			}
		}
		return serviceMethodHandlerMap;
	}

}
